import React, { useRef, useState, useEffect } from 'react';
import { Button, Select, Records, Tag, notification, Tooltip, Modal } from '@block/plug';
import { $fetch, datejs } from '@block/utils';
import { MenuCode, LimitsAuthority } from '@src/utils';
import { InterfaceModel } from './elements';
import { TableRow, TableRequest, PersonType } from './types';
import Url from './url';
import './index.scss';

const { Form, Table } = Records;

const POP_LAYER = {
  getContainer: (): HTMLElement => document.querySelector('.interface-person-manage-content') || document.body,
};

/**
 * 敏感岗位-接口人管理列表页
 */
const InterfacePersonManage = () => {
  /** state 定义 */
  const [rowInfo, setRowInfo] = useState<TableRow>();
  const [modelVisible, setModelVisible] = useState(false);
  const [selectedKeys, setSelectedKeys] = useState([]);
  const [pageActions, setPageActions] = useState<Array<LimitsAuthority>>([]); // 页面操作权限
  const allDelBtnDisable = !(selectedKeys.length > 0); // 批量删除禁选

  /** ref 定义 */
  const recordsRef = useRef<Records>();

  /** 获取页面初始化数据 */
  const getInitData = async () => {
    const res = await $fetch<Array<LimitsAuthority>>(Url.queryPermissionListByMenu, {
      menuCode: MenuCode.senPosInterfacePersonManage,
    });
    setPageActions(res || []);
  };

  /** DidMount */
  useEffect(() => {
    getInitData();
  }, []);

  /**
   * 列表数据请求
   * @param filter 筛选条件
   * @param Page 分页信息
   * @returns 列表数据
   */
  const onSearch = async (filter: any, page: Page) => {
    const params: TableRequest = {
      privilegeOrgIdList: filter?.orgIdList?.map((org: SelectOption) => org?.code),
      empId: filter?.interfacePersonEmpId?.code,
      interfacePersonType: filter?.interfacePersonTypeName?.code,
      interfacePersonStatus: filter?.authMatterId?.code,
    };
    // 清空之前的勾选数据
    setSelectedKeys([]);
    const data: Pagination<TableRow> = await $fetch(Url.pageList, { cond: { ...params }, page });
    return data;
  };

  /** 关闭弹窗处理 */
  const handleCloseModel = () => {
    setModelVisible(false);
    recordsRef.current.search(1);
  };

  /** 重置按钮事件 */
  const handleReset = () => {
    recordsRef.current.resetFilterValue().then(() => {
      recordsRef.current.search(1);
    });
  };

  /**
   * 删除行
   * @param row 行数据
   */
  const handleDel = async (row: TableRow) => {
    Modal.warning({
      title: '提示',
      message: '确认删除吗？',
      closable: true,
      onOk: async () => {
        const resData = await $fetch<OperateResponse>(Url.deleteInterfacePerson, {
          interfacePersonId: row?.interfacePersonId,
        });
        notification.success({ title: '成功', message: resData?.message || '删除成功' });
        recordsRef.current?.search(1);
      },
      okText: '确定',
      cancelText: '取消',
    });
  };

  /** 批量删除 */
  const handleAllDel = async () => {
    Modal.warning({
      title: '提示',
      message: '确认批量删除吗？',
      closable: true,
      onOk: async () => {
        const resData = await $fetch<OperateResponse>(Url.batchDeleteInterfacePerson, {
          interfacePersonIdList: selectedKeys?.map((id) => id),
        });
        notification.success({ title: '成功', message: resData?.message || '删除成功' });
        recordsRef.current?.search(1);
      },
      okText: '确定',
      cancelText: '取消',
    });
  };

  /**
   * 表格行选中Change
   * @param selectedRows 选中的行数据
   */
  const handleSelectChange = (selectedRows) => {
    setSelectedKeys(selectedRows);
  };

  /** 点击新建btn */
  const handleAddBtn = () => {
    setModelVisible(true);
    setRowInfo(null);
  };

  /**
   * 点击编辑btn
   * @param row 行数据
   */
  const handleEditBtn = (row: TableRow) => {
    setModelVisible(true);
    setRowInfo(row);
  };

  return (
    <div className="interface-person-manage">
      <div className="interface-person-manage-header">
        <div className="header-title">
          <span>接口人管理页面</span>
        </div>
        <div className="header-btns">
          {pageActions.includes(LimitsAuthority.add) && (
            <Button
              type="primary"
              onClick={() => {
                handleAddBtn();
              }}
            >
              新建
            </Button>
          )}
        </div>
      </div>
      <div className="interface-person-manage-content">
        <Records
          onSearch={onSearch}
          ref={recordsRef}
          pagination={{ defaultPageSize: 20, showQuickJumper: true, showSizeChanger: true, showTotal: true }}
        >
          <Form labelWidth={120}>
            <Form.Item span="8" formItemKey="orgIdList" label="适用组织：">
              <Select
                toFormItem
                multiple
                maxTagCount={5}
                popLayer={POP_LAYER}
                keyField="code"
                labelField="name"
                onFetchData={(search: string) =>
                  $fetch<SelectOption<string>[]>(Url.queryOrgList, { search: search?.trim() || ' ' })
                }
                placeholder="请选择适用组织"
              />
            </Form.Item>
            <Form.Item span="8" formItemKey="interfacePersonEmpId" label="接口人：">
              <Select
                toFormItem
                keyField="code"
                labelField="name"
                popLayer={POP_LAYER}
                onFetchData={(search: string) =>
                  $fetch<SelectOption<string>[]>(Url.queryEmployeeList, { search: search?.trim() || ' ' })
                }
                placeholder="请选择接口人"
                dispatchFetchDataWithoutKeyword={false}
              />
            </Form.Item>
            <Form.Item span="8" formItemKey="interfacePersonTypeName" label="接口人类型：">
              <Select
                toFormItem
                keyField="code"
                labelField="name"
                popLayer={POP_LAYER}
                filterable={false}
                onFetchData={() => $fetch<SelectOption<string>[]>(Url.queryInterfacePersonTypeList)}
                placeholder="请选择接口人类型"
              />
            </Form.Item>
            <Form.Item span="8" formItemKey="authMatterId" label="状态：">
              <Select
                toFormItem
                keyField="code"
                labelField="name"
                popLayer={POP_LAYER}
                filterable={false}
                onFetchData={() => $fetch<SelectOption<string>[]>(Url.queryInterfacePersonStatusList)}
                placeholder="请选择状态"
              />
            </Form.Item>
            <Form.Item span="8" />
            <Form.Item span="8">
              <div className="search-btns">
                <Button type="primary" shape="text" onClick={handleReset}>
                  重置
                </Button>
                <Button
                  ghost
                  type="primary"
                  onClick={() => recordsRef.current.search(1)}
                  className="search-btns-search"
                >
                  查询
                </Button>
              </div>
            </Form.Item>
          </Form>
          {pageActions.includes(LimitsAuthority.batchDelete) && (
            <Button type="primary" disabled={allDelBtnDisable} onClick={handleAllDel}>
              批量删除
            </Button>
          )}
          <Table
            scroll={{ x: true }}
            rowKey="interfacePersonId"
            rowSelection={{ fixed: 'left', selectedKeys }}
            onSelectChange={handleSelectChange}
          >
            <Table.Column dataKey="interfacePersonEmpName" width={100}>
              接口人
            </Table.Column>
            <Table.Column dataKey="interfacePersonTypeName" width={100}>
              接口人类型
            </Table.Column>
            <Table.Column
              dataKey="privilegeOrgNamePath"
              width={160}
              render={(value) =>
                value.length > 20 ? (
                  <Tooltip message={<div style={{ fontSize: '12px' }}>{value}</div>}>
                    {`${value.split('-')[0]}/.../${value.split('-')[value.split('-').length - 1]}`}
                  </Tooltip>
                ) : (
                  value
                )
              }
            >
              适用组织
            </Table.Column>
            <Table.Column
              dataKey="interfacePersonStatus"
              width={55}
              render={(val: number) => {
                return val === PersonType.has ? <Tag theme="green">有效</Tag> : <Tag theme="gray">失效</Tag>;
              }}
            >
              状态
            </Table.Column>
            <Table.Column dataKey="creatorEmpName" width={110} render={(value) => value ?? '-'}>
              创建人
            </Table.Column>
            <Table.Column
              dataKey="createTime"
              width={130}
              render={(date: number) => (date ? datejs(date)?.format('YYYY-MM-DD HH:mm:ss') : '-')}
            >
              创建时间
            </Table.Column>
            <Table.Column
              dataKey="authMatterTypeName"
              width={80}
              render={(_, row: TableRow) => (
                <div style={{ display: row?.actions.length > 0 ? 'block' : 'none' }}>
                  <Button
                    type="primary"
                    shape="text"
                    onClick={() => {
                      handleEditBtn(row);
                    }}
                  >
                    编辑
                  </Button>
                  <Button
                    type="primary"
                    shape="text"
                    onClick={() => {
                      handleDel(row);
                    }}
                  >
                    删除
                  </Button>
                </div>
              )}
            >
              操作
            </Table.Column>
          </Table>
        </Records>
      </div>
      {modelVisible && <InterfaceModel onClose={() => handleCloseModel()} row={rowInfo} />}
    </div>
  );
};

export default InterfacePersonManage;
